<template>
  <span
    v-if="left > 0"
  >{{day > 0 ? day + '天' : ''}}{{hour > 0 ? hour + '时' : ''}}{{minute > 0 ? minute + '分' : ''}}{{second >0 ? second + '秒' : ''}}</span>
  <span v-else>（已结束）</span>
</template>

<script>
export default {
  props: {
    leftTime: {
      type: [Number, String]
    }
  },
  data() {
    return {
      timeout: false,
      timer: null,
      left: this.leftTime
    };
  },
  mounted() {
    this.countdown();
  },
  beforeDestroy() {
    if (this.timer) {
      clearTimeout(this.timer);
    }
  },
  computed: {
    // 服务端返回时间毫秒 => 秒
    day() {
      return Math.floor(this.left / 60 / 60 / 24);
    },
    hour() {
      return Math.floor((this.left / 60 / 60) % 24);
    },
    minute() {
      return Math.floor((this.left / 60) % 60);
    },
    second() {
      return Math.floor(this.left % 60);
    }
  },
  methods: {
    countdown() {
      if (!this.left && this.left != 0) {
        this.timeout = true;
        return;
      }
      this.left--;
      if (this.left > 0) {
        this.timer = setTimeout(this.countdown, 1000);
      } else {
        clearTimeout(this.timer);
        this.timeout = true;
        this.$emit("timeUp");
      }
    }
  }
};
</script>